<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.name" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入昵称"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData">
        <el-table-column prop="username" label="账号" />
        <el-table-column prop="avatar" label="头像">
          <template v-slot="scope">
            <el-image style="width: 40px; height: 40px; border-radius: 50%; display: block" v-if="scope.row.avatar"
                      :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" preview-teleported>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="昵称" />
        <el-table-column prop="role" label="角色">
          <template #default="scope">
            <div v-if=" scope.row.role === 'USER' ">普通用户</div>
            <div v-if=" scope.row.role === 'PETSHOP' ">宠物店</div>
            <div v-if=" scope.row.role === 'ADMIN' ">管理员</div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="email" label="邮箱" />
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination
          @current-change="load"
          @size-change="handleSizeChange"
          background layout="total, prev, pager, next, jumper, sizes"
          :page-sizes="[1, 3, 5, 10, 15, 20, 30]"
          :page-size="data.pageSize"
          v-model:current-page="data.pageNum"
          :total="data.total"/>
    </div>
  </div>
</template>
<script setup>
  import {reactive, ref} from 'vue'
  import request from '@/utils/request.js'
  import { ElMessage } from 'element-plus'


  const data = reactive({
    pageNum: 1,
    pageSize: 10,
    name: null,
    tableData: [],
    total: 0,
  })

  const load = () => {
    request.get('/user/pageQuery', {
      params:{
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        name: data.name
      }
    }).then(res => {
      if (res.code === '200') {
        data.tableData = res.data?.list || []
        data.total = res.data?.total
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  const reset = () => {
    data.name = null;
    load()
  }

  const handleSizeChange = (newSize) => {
    data.pageSize = newSize
    data.pageNum = 1
    load()
  }

  load()
</script>